<?php

class Configuration {

    protected $path;
    protected $data;
    protected $_autoCreate;
    protected $_autoSave;

    static protected function get_ini_string($Array) {
        $result = null;
        foreach($Array as $key => $element) {
            if (is_array($element)) {
                $result.= PHP_EOL;
                $result.= '['.$key.']'.PHP_EOL;
                $result.= self::get_ini_string($element).PHP_EOL;
            } else {
                $result.= $key.' = "'.$element.'"'.PHP_EOL;
            }
        }
        return (string) $result;
    }

    static public function getByPath($path, $save = false, $create = true) {
        $result = new Configuration();
        $result->setPath($path);
        $result->_autoSave   = $save;
        $result->_autoCreate = $create;
        if (!file_exists($path)) {
            if ($result->_autoCreate) {
                $handle = fopen($result->path, 'w');
                if (is_resource($handle)) {
                    fclose($handle);
                } else {
                    throw new Exception('Impossible de créer le fichier');
                }
            } else {
                throw new Exception('');
            }
        } else {
            $result->load();
        }
        return $result;
    }

    private function __construct() {}

    public function __destruct() {
        if ($this->_autoSave) {
            $this->save();
        }
    }

    public function __toString() {
        return (string) self::get_ini_string($this->data);
    }

    public function __get($name) {
        return $this->data[$name];
    }

    public function __set($name, $value) {
        return $this->data[$name][$value[0]] = $value[1];
    }

    protected function setPath($path) {
        if (is_string($path)) {
            $this->path = $path;
        } else {
            throw new InvalidArgumentException('Nom de fichier invalide');
        }
        return $this;
    }

    protected function setData($data) {
        if (is_array($data)) {
            $this->data = $data;
        } else {
            throw new InvalidArgumentException('Données invalides');
        }
        return $this;
    }

    public function load() {
        return $this->setData(parse_ini_file($this->path, true));
    }

    public function save() {
        file_put_contents($this->path, (string) $this);
        return $this;
    }

}

?>